from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from .models import ArticleFavorite
from ..models import Article


@login_required
def list(request):
    favorites = ArticleFavorite.objects.filter(user=request.user)

    curfilter = request.GET.get('filter', 'all')
    if curfilter == 'translated':
        favorites = favorites.filter(article__status=Article.TRANSLATED)
    elif curfilter == 'schedule':
        favorites = favorites.filter(article__status=Article.APPROVED)

    cursort = request.GET.get('sort', 'date')
    if cursort == 'views':
        favorites = favorites.order_by('-article__view_count')

    paginator = Paginator(favorites, 10)
    page = request.GET.get('page')
    try:
        favorites = paginator.page(page)
    except PageNotAnInteger:
        favorites = paginator.page(1)
    except EmptyPage:
        favorites = paginator.page(paginator.num_pages)

    filter_urls = {}
    url_get_params = request.GET.copy()
    url_get_params['filter'] = 'all'
    filter_urls['all'] = '?' + url_get_params.urlencode()
    url_get_params['filter'] = 'translated'
    filter_urls['translated'] = '?' + url_get_params.urlencode()
    url_get_params['filter'] = 'schedule'
    filter_urls['schedule'] = '?' + url_get_params.urlencode()

    sort_urls = {}
    url_get_params = request.GET.copy()
    url_get_params['sort'] = 'date'
    sort_urls['date'] = '?' + url_get_params.urlencode()
    url_get_params['sort'] = 'views'
    sort_urls['views'] = '?' + url_get_params.urlencode()

    return render(request, 'translations/favorites/list.html', {'favorites': favorites,
                            'filter_urls': filter_urls, 'sort_urls': sort_urls, 'curfilter': curfilter, 'cursort': cursort})


@login_required
def create(request, article_id):
    if request.is_ajax() and request.method == 'POST':
        article = get_object_or_404(Article, pk=article_id)

        favorites = ArticleFavorite.objects.filter(user=request.user, article=article)
        if not favorites.exists():
            ArticleFavorite(user=request.user, article=article).save()

        count = ArticleFavorite.objects.filter(article=article).count()
        return HttpResponse(count)
    else:
        raise Http404


@login_required
def delete(request, article_id):
    if request.is_ajax() and request.method == 'POST':
        article = get_object_or_404(Article, pk=article_id)

        favorite = get_object_or_404(ArticleFavorite, user=request.user, article=article)
        favorite.delete()
        
        count = ArticleFavorite.objects.filter(article=article).count()
        return HttpResponse(count)
    else:
        raise Http404
